package com.demo.practiceui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.demo.practiceui.views.animation.DashboardAnimView;
import com.demo.practiceui.views.animation.LoadingRingView;
import com.demo.practiceui.views.animation.ParticleView;
import com.demo.practiceui.views.animation.TextEffectView;
import com.demo.practiceui.views.animation.WaveView;
import com.demo.practiceui.views.animation.wave;
import com.demo.practiceui.views.chart.BarChartView;
import com.demo.practiceui.views.chart.DashboardView;
import com.demo.practiceui.views.chart.DonutChartView;
import com.demo.practiceui.views.chart.HeatMapView;
import com.demo.practiceui.views.chart.RadarChartView;
import com.demo.practiceui.views.interactive.CountDownView;
import com.demo.practiceui.views.interactive.CustomProgressView;
import com.demo.practiceui.views.interactive.CustomSwitchView;
import com.demo.practiceui.views.interactive.DragSortView;
import com.demo.practiceui.views.interactive.SlideUnlockView;
import com.demo.practiceui.views.interactive.drag;
import com.demo.practiceui.views.interactive.mycustomprogress;
import com.demo.practiceui.views.interactive.sidler;
import com.demo.practiceui.views.interactive.swich;

/**
 * ViewPager2 适配器
 * 用于展示15个自定义View，支持左右滑动
 */
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {

    private Context context;
    
    // 保存每个位置的View引用，用于控制动画
    private android.util.SparseArray<View> viewCache = new android.util.SparseArray<>();
    
    // View页面信息
    public static class PageInfo {
        String title;
        String category;
        String description;

        PageInfo(String title, String category, String description) {
            this.title = title;
            this.category = category;
            this.description = description;
        }
    }

    // 15个页面信息
    private final PageInfo[] pages = {
            // 数据可视化类
            new PageInfo("柱状图 (Bar Chart)", "📊 数据可视化", "用于展示数据对比，如销量、成绩统计"),
            new PageInfo("环形图 (Donut Chart)", "📊 数据可视化", "展示数据占比，比扇形图更美观"),
            new PageInfo("仪表盘 (Dashboard)", "📊 数据可视化", "速度表、电量显示、进度监控"),
            new PageInfo("雷达图 (Radar Chart)", "📊 数据可视化", "多维度能力评估，如用户能力雷达"),
            new PageInfo("热力图 (Heat Map)", "📊 数据可视化", "用户行为分布、区域热度统计"),
            
            // 交互控件类
            new PageInfo("自定义进度条 (Progress)", "🎮 交互控件", "线性和圆形两种进度显示"),
            new PageInfo("滑动解锁 (Slide Unlock)", "🎮 交互控件", "滑动确认操作，防误触"),
            new PageInfo("倒计时 (CountDown)", "🎮 交互控件", "验证码倒计时（点击开始）"),
            new PageInfo("自定义开关 (Switch)", "🎮 交互控件", "功能开启/关闭控制"),
            new PageInfo("拖拽排序 (Drag Sort)", "🎮 交互控件", "列表拖拽排序、任务优先级"),
            
            // 动画特效类
            new PageInfo("波浪动画 (Wave)", "✨ 动画特效", "水位显示、加载动画、背景动效（自动播放）"),
            new PageInfo("粒子效果 (Particle)", "✨ 动画特效", "爆炸特效、点赞动效（点击屏幕触发）"),
            new PageInfo("加载圆环 (Loading Ring)", "✨ 动画特效", "页面加载中、数据加载等待（自动播放）"),
            new PageInfo("仪表盘动画 (Dashboard Anim)", "✨ 动画特效", "数据刷新动效、状态切换（自动播放）"),
            new PageInfo("文字动效 (Text Effect)", "✨ 动画特效", "标题强调、提示文字高亮（自动播放）")
    };

    public ViewPagerAdapter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建页面布局
        LinearLayout layout = new LinearLayout(context);
        layout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(32, 32, 32, 32);
        
        return new ViewHolder(layout);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        LinearLayout container = (LinearLayout) holder.itemView;
        container.removeAllViews();

        PageInfo pageInfo = pages[position];

        // 添加描述文字
        TextView tvDescription = new TextView(context);
        tvDescription.setText(pageInfo.description);
        tvDescription.setTextSize(14);
        tvDescription.setTextColor(0xFF666666);
        tvDescription.setPadding(0, 0, 0, 24);
        container.addView(tvDescription);

        // 根据位置添加对应的自定义View
        View customView = createCustomView(position);
        if (customView != null) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            customView.setLayoutParams(params);
            container.addView(customView);
            
            // 缓存View引用，用于后续控制动画
            viewCache.put(position, customView);
        }
    }

    /**
     * 创建自定义View
     */
    private View createCustomView(int position) {
        View view = null;
        
        switch (position) {
            case 0: // 柱状图
                BarChartView barChart = new BarChartView(context);
                float[] barData = {65, 85, 45, 92, 73, 88, 56};
                String[] barLabels = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
                barChart.setData(barData, barLabels);
                view = barChart;
                break;

            case 1: // 环形图
                view = new DonutChartView(context);
                break;

            case 2: // 仪表盘
                view = new DashboardView(context);
                break;

            case 3: // 雷达图
                RadarChartView radarChart = new RadarChartView(context);
                float[] radarData = {85, 75, 90, 65, 80};
                String[] radarLabels = {"攻击", "防御", "速度", "技能", "体力"};
                radarChart.setData(radarData, radarLabels);
                view = radarChart;
                break;

            case 4: // 热力图
                view = new HeatMapView(context);
                break;

            case 5: // 自定义进度条（线性和圆形）
                // 创建一个容器，同时显示两种进度条
                LinearLayout progressContainer = new LinearLayout(context);
                progressContainer.setOrientation(LinearLayout.VERTICAL);
                progressContainer.setPadding(0, 20, 0, 20);
                
                // 线性进度条
                mycustomprogress linearProgress = new mycustomprogress(context);
                linearProgress.setCircular(false);
                linearProgress.setProgress(35);
                LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, 200);
                linearParams.bottomMargin = 40;
                linearProgress.setLayoutParams(linearParams);
                progressContainer.addView(linearProgress);
                
                // 圆形进度条
                CustomProgressView circularProgress = new CustomProgressView(context);
                circularProgress.setCircular(true);
                circularProgress.setProgress(75);
                LinearLayout.LayoutParams circularParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, 
                        ViewGroup.LayoutParams.MATCH_PARENT);
                circularProgress.setLayoutParams(circularParams);
                progressContainer.addView(circularProgress);
                
                view = progressContainer;
                break;

            case 6: // 滑动解锁
                view = new sidler(context);
                break;

            case 7: // 倒计时
                CountDownView countDown = new CountDownView(context);
                countDown.setTotalTime(60);
                // 添加点击启动倒计时
                countDown.setOnClickListener(v -> {
                    countDown.start();
                });
                view = countDown;
                break;

            case 8: // 自定义开关
                view = new swich(context);
                break;

            case 9: // 拖拽排序
                view = new drag(context);
                break;

            case 10: // 波浪动画
                view = new wave(context);
                break;

            case 11: // 粒子效果
                ParticleView particleView = new ParticleView(context);
                particleView.setOnClickListener(v -> {
                    particleView.explode(v.getWidth() / 2f, v.getHeight() / 2f);
                });
              
                view = particleView;
                break;

            case 12: // 加载圆环
                view = new LoadingRingView(context);
                break;

            case 13: // 仪表盘动画
                view = new DashboardAnimView(context);
                break;

            case 14: // 文字动效
                view = new TextEffectView(context);
                break;
        }

        return view;
    }

    @Override
    public int getItemCount() {
        return pages.length;
    }

    /**
     * 获取页面信息
     */
    public PageInfo getPageInfo(int position) {
        if (position >= 0 && position < pages.length) {
            return pages[position];
        }
        return null;
    }
    
    /**
     * 暂停指定位置的动画
     */
    public void pauseAnimations(int position) {
        View view = viewCache.get(position);
        if (view == null) return;
        
        // 根据View类型暂停动画
        if (view instanceof WaveView) {
            ((WaveView) view).pause();
        } else if (view instanceof ParticleView) {
            ((ParticleView) view).pause();
        } else if (view instanceof LoadingRingView) {
            ((LoadingRingView) view).setLoading(false);
        } else if (view instanceof TextEffectView) {
            ((TextEffectView) view).pause();
        } else if (view instanceof CountDownView) {
            ((CountDownView) view).pause();
        }
        // LinearLayout容器的情况（进度条页面）
        else if (view instanceof LinearLayout) {
            // 不需要特殊处理
        }
    }
    
    /**
     * 恢复指定位置的动画
     */
    public void resumeAnimations(int position) {
        View view = viewCache.get(position);
        if (view == null) return;
        
        // 根据View类型恢复动画
        if (view instanceof WaveView) {
            ((WaveView) view).resume();
        } else if (view instanceof LoadingRingView) {
            ((LoadingRingView) view).setLoading(true);
        } else if (view instanceof TextEffectView) {
            ((TextEffectView) view).resume();
        }
        // 粒子效果需要点击触发，不自动恢复
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

